package com.socket_1;

import io.netty.channel.nio.NioEventLoop;

import java.io.IOException;
import java.net.Socket;
import java.util.concurrent.TimeUnit;

/**
 * @author sijunqiang
 * @data 2021/7/30 23:13
 * @description: 模拟客户端发送消息
 */
public class Client {


    private static final String HOST = "127.0.0.1";
    private static final int PORT = 8000;


    public static void main(String[] args) throws IOException {
        //创建一个socket客户端对象 用于连接服务端 用户两台机器的连接
        final Socket socket = new Socket(HOST, PORT);

        new Thread(new Runnable() {
            public void run() {
                System.out.println("客户端启动成功!");
                while (true) {
                    try {
                        //这是客户端要发送的消息
                        String message = "hello,world";
                        System.out.println("客户端发送数据：" + message);
                        // 获取输出流 并将数据写出去
                        socket.getOutputStream().write(message.getBytes());
                    } catch (IOException e) {
                        e.printStackTrace();
                        System.out.println("写数据出错！");
                    }
                    // 休息5s 再次的发送消息
                    sleep();
                }
            }
        }).start();

    }

    private static void sleep() {
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
